package cors

import (
	"fmt"

	"apiGateWay/internal/config"

	"github.com/gin-gonic/gin"
)

// CORSMiddleware CORS 中间件
func CORSMiddleware(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.Request.Header.Get("Origin")

		// 检查源是否在允许列表中
		allowed := false
		if len(cfg.CORS.AllowOrigins) == 0 || cfg.CORS.AllowOrigins[0] == "*" {
			allowed = true
		} else {
			for _, allowedOrigin := range cfg.CORS.AllowOrigins {
				if origin == allowedOrigin {
					allowed = true
					break
				}
			}
		}

		if allowed {
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		}

		if cfg.CORS.AllowCredentials {
			c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		}

		c.Writer.Header().Set("Access-Control-Allow-Methods", joinStrings(cfg.CORS.AllowMethods, ","))
		c.Writer.Header().Set("Access-Control-Allow-Headers", joinStrings(cfg.CORS.AllowHeaders, ","))
		c.Writer.Header().Set("Access-Control-Max-Age", fmt.Sprintf("%d", cfg.CORS.MaxAge))

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}

func joinStrings(strs []string, sep string) string {
	if len(strs) == 0 {
		return ""
	}
	result := strs[0]
	for i := 1; i < len(strs); i++ {
		result += sep + strs[i]
	}
	return result
}

